import java.io.File;
import java.io.IOException;
import java.util.Scanner;

// -------------------------------------------------------------------------
/**
 *  Reads the given input file. Pulls and executes all commands from the file.
 *
 *  @author Erik Rodriguez and Cory Chase
 *  @version Mar 21, 2013
 */
public class CommandParser {
	private File inputFile;         //The input file given when the rpogram is run
	private FileManager fileManager; //The filemanager to write to the file
	private HashTable hashTable;    //The hash table

	// ----------------------------------------------------------
	/**
	 * Create a new CommandParser object. Pass in the tree to perform commands on
	 * and the input file. Create a new list of commands.
	 * @param input the input file
	 * @param fileManager the file manager
	 * @param hashTable the hash table
	 * @throws IOException
	 */
	public CommandParser(File input, FileManager fileManager, HashTable hashTable) throws IOException{
		this.inputFile = input;
		this.fileManager = fileManager;
		this.hashTable = hashTable;
	}

	// ----------------------------------------------------------
	/**
	 * Read through the input file and find all commands and add them to a list
	 * to be executed.
	 * @throws IOException
	 */
	@SuppressWarnings("resource")
    public void parseCommands() throws IOException{

		Scanner input = new Scanner(inputFile);
		while(input.hasNextLine()){
			String line = input.nextLine();
			line = line.replaceAll("\\s", "");  //Remove all blank spaces fro mthe line
			if(!line.isEmpty()){
				if(line.startsWith("insert")){ //Insert command
					line = line.replaceAll("insert", ""); //What is left is the parameter
					String seqID = line.replaceAll("[0-9]", "");
					String sequence = input.nextLine().trim();
					Command tempCommand = new Command(Globals.INSERT_COMMAND,sequence, seqID, fileManager, hashTable);
					tempCommand.execute();
				}
				else if(line.startsWith("remove")){ //Remove command
					line = line.replaceAll("remove", ""); //What is left is the parameter
					Command tempCommand = new Command(Globals.REMOVE_COMMAND,line, fileManager, hashTable);
					tempCommand.execute();
				}
				else if(line.startsWith("print")){ //Normal print command
					Command tempCommand = new Command(Globals.PRINT_COMMAND, fileManager, hashTable);
					tempCommand.execute();
				}
				else if(line.startsWith("search")){  //Search command
					line = line.replaceAll("search", ""); //What is left is the parameter
					Command tempCommand = new Command( Globals.SEARCH_COMMAND, line, fileManager, hashTable);
					tempCommand.execute();
				}
			}
		}

	}


}
